#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
from __future__ import print_function

from flask import render_template, \
    redirect, url_for, flash

from . import Nao
from . import camManger
from . import forms
from . import main

#================= 采集 ===============
@main.route('/collection', methods=['GET', 'POST'])
def collection():
    #flash(session)
    page_title = u"采集"
    urls = [
        {
            "url": url_for('.select_cam'),
            "text": u"指定相机"
        }]
    cam = camManger.get_current_cam()
    if cam is not None:
        from . import flag
        collect_url = url_for('.collect_camera', cam_id=cam.id, image_flags=flag.image.collect)
        urls.append({"url": collect_url,
                    "text": u"采集相机数据"})
    return render_template('index.html',page_title=page_title,urls=urls)

@main.route('/select_cam', methods=['GET', 'POST'])
def select_cam():
    if Nao.get_names() == []:
        flash(u"数据库中没有Nao，需要先向数据库Nao中添加")
        return redirect(url_for(".index"))
    cam = camManger.get_current_cam()
    if cam is None:
        form = forms.SelectCamForm()
    else:
        nao = Nao.get(cam.nao_id)
        form = forms.SelectCamForm(nao_name=nao.name,position=cam.position)

    form.nao_name.choices=zip(Nao.get_names(), Nao.get_names())

    if form.validate_on_submit():
        nao_name = form.nao_name.data
        position = form.position.data
        nao = Nao.get_by_name(nao_name)
        cam = nao.get_cam(position)
        if not camManger.has(cam):
            camManger.add(cam)
        camManger.set_current_cam(cam)
        return redirect(url_for(".index"))
    return render_template('form.html',name=u"指定相机",form=form)

@main.route('/collection/camera/<int:cam_id>/<image_flags>', methods=['GET', 'POST'])
def collect_camera(cam_id, image_flags):
    """采集单个相机图像"""
    assert camManger.has(cam_id)
    btns = [
        {
            "id": "saveImage",
            "name": u"保存图像",
            "api": url_for("api.save_image",cam_id=cam_id,image_flag=image_flags)
        }
    ]
    cam = camManger.get(cam_id=cam_id)
    return render_template('cam.html', cam_name=cam.name, btns=btns,cam_id=cam.id)